import json
import os
import sys

import requests

token = None


def get_token(ci_url):
    username = os.getenv('JIANMU_CI_USERNAME')
    password = os.getenv('JIANMU_CI_PASSWORD')
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        'username': username,
        'password': password
    }
    response = requests.post(url=ci_url + '/auth/login', headers=headers, data=json.dumps(data))
    result = response.json()
    if result.get('statusCode'):
        # TODO 兼容auth-mode为false
        if result.get('message') == 'There is no PasswordEncoder mapped for the id "null"':
            return
        print("error: 登陆失败；", result.get('message'), flush=True)
        sys.exit(1)
    global token
    token = result.get('type') + " " + result.get('token')


def get_projects(ci_url, page_num, group_id):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    params = {
        "pageNum": page_num,
        "pageSize": 10000,
        "projectGroupId": group_id
    }
    response = requests.get(url=ci_url + '/view/v2/projects', headers=headers, params=params)
    return response.json()


def get_project_detail(ci_url, project_id):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    response = requests.get(url=ci_url + '/view/projects/' + project_id, headers=headers)
    return response.json()


def create_project(ci_url, group_id, name, config_file, dsl_text):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'dslText': dsl_text,
        'projectGroupId': group_id
    }
    response = requests.post(url=ci_url + '/projects', headers=headers, data=json.dumps(data))
    if 200 == response.status_code:
        print('success:', name + "；", config_file + "；", '创建成功', flush=True)
        return True
    result = response.json()
    if result.get('statusCode'):
        print('error:', name + "；", config_file + "；", '创建失败；', result.get('message'), flush=True)
    return False


def update_project(ci_url, group_id, name, project_id, config_file, dsl_text):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'dslText': dsl_text,
        'projectGroupId': group_id
    }
    response = requests.put(url=ci_url + '/projects/' + project_id, headers=headers, data=json.dumps(data))
    if 200 == response.status_code:
        print('success:', name + "；", config_file + "；", '项目dsl内容有变化，同步更新', flush=True)
        return True
    result = response.json()
    if result.get('statusCode'):
        print('error:', name + "；", config_file + "；", '更新失败；', result.get('message'), flush=True)
        return False


def delete_project(ci_url, project_id, name):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    response = requests.delete(url=ci_url + '/projects/' + project_id, headers=headers)
    if 200 == response.status_code:
        print('success:', name + "；", '删除成功', flush=True)
        return
    result = response.json()
    if result.get('statusCode'):
        print('error:', name + "；", '删除失败；', result.get('message'), flush=True)


def get_project_groups(ci_url):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    response = requests.get(url=ci_url + '/view/projects/groups', headers=headers)
    return response.json()


def create_project_group(ci_url, name):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'name': name,
        'isShow': True
    }
    response = requests.post(url=ci_url + '/projects/groups', headers=headers, data=json.dumps(data))
    if 200 == response.status_code:
        print('success:', '项目组', name, '创建成功', flush=True)
        return True
    result = response.json()
    if result.get('statusCode'):
        print('error:', '项目组', name, '创建失败；', result.get('message'), flush=True)
        return False


def add_project(ci_url, project_group_id, project_id, origin_name, name, project_name, config_file):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'projectGroupId': project_group_id,
        'projectIds': [project_id]
    }
    response = requests.post(url=ci_url + '/projects/groups/projects', headers=headers, data=json.dumps(data))
    if 200 == response.status_code:
        print('success:', project_name + "；", config_file + "；", '从' + origin_name + '移到' + name + '项目组，成功', flush=True)
        return
    result = response.json()
    if result.get('statusCode'):
        print('error:', project_name + "；", config_file + "；", '从' + origin_name + '移到' + name + '项目组，失败',
              result.get('message'), flush=True)


def update_project_sort(ci_url, group_id, source_id, target_id):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'originProjectId': source_id,
        'targetProjectId': target_id
    }
    response = requests.patch(url=ci_url + '/projects/groups/' + group_id + '/projects/sort', headers=headers,
                              data=json.dumps(data))
    if 200 == response.status_code:
        return None
    result = response.json()
    if result.get('statusCode'):
        return result.get('message')


def update_group_sort(ci_url, source_id, target_id):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': token
    }
    data = {
        'originGroupId': source_id,
        'targetGroupId': target_id
    }
    response = requests.patch(url=ci_url + '/projects/groups/sort', headers=headers,
                              data=json.dumps(data))
    if 200 == response.status_code:
        return None
    result = response.json()
    if result.get('statusCode'):
        return result.get('message')
